﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using WP8.EmpezandoComunicacion.Classes;
using System.IO;
using PCL.WP8.Common.Domain;
using PCL.WP8.Demo;

namespace WP8.EmpezandoComunicacion.Pages
{
    public partial class ConsumiendoRESTPage : PhoneApplicationPage
    {
        public ConsumiendoRESTPage()
        {
            InitializeComponent();
        }

        private void WebClient_Click(object sender, RoutedEventArgs e)
        {
            WebClient webClient = new WebClient();
            webClient.DownloadStringCompleted += (s, a) =>
            {
                if (null == a.Error)
                {
                    var json = a.Result;
                    var participantes = ObjectJsonSerializer<List<Participante>>.FromJson(json);
                    this.lb.ItemsSource = participantes;
                }
            };
            webClient.DownloadStringAsync(new Uri("http://wawp8demo.azurewebsites.net/api/participantes", UriKind.Absolute));
        }

        private void HttpRequest_Click(object sender, RoutedEventArgs e)
        {
            HttpWebRequest httpWebRequest = HttpWebRequest.CreateHttp("http://wawp8demo.azurewebsites.net/api/participantes");
            httpWebRequest.Method = "GET";
            httpWebRequest.BeginGetResponse(ar =>
            {
                var httpRequest = (HttpWebRequest)ar.AsyncState;
                var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(ar);
                var responseStream = httpResponse.GetResponseStream();
                using (var reader = new StreamReader(responseStream))
                {
                    var json = reader.ReadToEnd();
                    var participantes = ObjectJsonSerializer<List<Participante>>.FromJson(json);
                    this.Dispatcher.BeginInvoke(() => this.lb.ItemsSource = participantes);
                }
            }, httpWebRequest);
        }

        private async void HttClient_Click(object sender, RoutedEventArgs e)
        {
            ParticipanteProxy clientProxy = new ParticipanteProxy();
            this.lb.ItemsSource = await clientProxy.Get();
        }

    }
}